package cn.kimming.rpc.remoting.registry;

import cn.kimming.rpc.common.exception.RpcException;
import cn.kimming.rpc.remoting.server.AbstractRpcServer;
import org.apache.curator.x.discovery.ServiceDiscovery;
import org.apache.curator.x.discovery.ServiceInstance;

import java.util.concurrent.ConcurrentHashMap;

public class UpdateServiceCallCountTask implements Runnable{

    private String serviceName;

    public UpdateServiceCallCountTask(String serviceName) {
        this.serviceName = serviceName;
    }

    @Override
    public void run() {
        ConcurrentHashMap<String, String> registerdServiceMap = AbstractRpcServer.getRegisterdServiceMap();
        String serviceId = registerdServiceMap.get(serviceName);
        ServiceDiscovery<InstanceDetail> discovery = ServerRpcRegistry.getDiscovery();
        try {
            synchronized (discovery) {
                ServiceInstance<InstanceDetail> instance = discovery.queryForInstance(serviceName, serviceId);
                if (instance != null) {
                    InstanceDetail detail = instance.getPayload();
                    detail.setCallCount(detail.getCallCount() + 1);
                    discovery.updateService(instance);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            throw new RpcException("更新被调用服务实例异常", e);
        }
    }
}
